import axios from '@/utils/axios'
import type {
  ArticleVO,
  Result,
  PageVO,
  ArticleCreateRequest,
  ArticleQueryParams,
  CategoryVO,
} from '@/types'

export const articleApi = {
  async getArticles(params: ArticleQueryParams): Promise<Result<PageVO<ArticleVO>>> {
    try {
      const response = await axios.get<Result<PageVO<ArticleVO>>>('/article/query/page', {
        params,
      })
      return response.data
    } catch (err) {
      console.error('文章列表请求错误:', err)
      throw err
    }
  },

  async getArticleById(id: number) {
    const response = await axios.get<Result<ArticleVO>>('/article/query/detail', {
      params: { articleId: id },
    })
    return response.data
  },

  async createOrUpdate(data: ArticleCreateRequest & { id?: number }) {
    const response = await axios.post<Result<boolean>>('/article/createOrUpdate', data)
    return response.data
  },

  async delete(id: number) {
    const response = await axios.delete<Result<boolean>>('/article/user/delete', {
      params: { id },
    })
    return response.data
  },

  async setLike(articleId: number, status: 1 | 2 | 3 | 4) {
    const response = await axios.post<Result<boolean>>('/article/liked', {
      articleId,
      status, // 1点赞 2取消点赞 3点踩 4取消点踩
    })
    return response.data
  },

  // 获取所有分类
  getCategories: async () => {
    const response = await axios.get<Result<CategoryVO[]>>('/article/query/category')
    return response.data
  },

  // 获取用户的文章列表
  async getUserArticles(userId: number): Promise<Result<ArticleVO[]>> {
    try {
      const response = await axios.get<Result<ArticleVO[]>>('/article/query/userArticles', {
        params: { userId },
      })
      return response.data
    } catch (err) {
      console.error('获取用户文章列表失败:', err)
      throw err
    }
  },
}
